package com.isoftstone.framework.aop;

import com.isoftstone.common.constant.Constants;
import com.isoftstone.common.utils.text.Convert;
import com.isoftstone.project.system.domain.SysLogOperate;
import com.isoftstone.project.system.service.ISysLogService;
import com.isoftstone.common.utils.JsonUtil;

import com.isoftstone.project.system.domain.SysUser;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 * 类名称：
 *
 * @author：guoX
 * @date: 2016/5/13
 *
 */
@Aspect
@Component
public class OpLogAspect {

    @Autowired
    @Qualifier("sysLogService")
    ISysLogService iSysLogService;

    @Pointcut("@annotation(com.isoftstone.framework.aop.OpLogAopController)")
    public void OpLogAopController(){
    }

    @AfterThrowing(throwing="e",pointcut="OpLogAopController()")
    public void doThrowing(JoinPoint joinPoint, Exception e) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        HttpSession session = request.getSession();
        String Path = request.getRequestURI();
        SysUser user = (SysUser)session.getAttribute(Constants.SESSION_USER);
        //请求的IP
        String ip = request.getRemoteAddr();
        //id
        String ID=  Convert.get32UUID();
        Map<String, Object>   map = null;
        try {
            map = getControllerMthodDescription(joinPoint);
            SysLogOperate log = new SysLogOperate();
            log.setLogId(ID);
            log.setUserId(user.getUserId());
            log.setUserName(user.getUserName());
            log.setUserIp(ip);
            log.setLogPath(Path);
            log.setLogModule((String) map.get("module"));
            String description= (String) map.get("description");
            if("0".equals(description)){
                log.setLogDesc((String) request.getAttribute("description")+e.getMessage());
            }else {
                log.setLogDesc((String) map.get("description")+e.getMessage());
            }
            log.setLogDate(new Date());
            log.setLogLevel("ERROR");
            log.setDeptName(user.getDeptId());
            Map properties = request.getParameterMap();
            if (properties != null) {
                log.setParameter(JsonUtil.beanToJson(properties));
            }
            iSysLogService.insertOperate(log);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }

    @After("OpLogAopController()")
    public void afterExec(JoinPoint joinPoint){
        MethodSignature ms=(MethodSignature) joinPoint.getSignature();
        Method method=ms.getMethod();
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            HttpSession session = request.getSession();
            String Path = request.getRequestURI();
            //读取session中的用户
            SysUser user = (SysUser)session.getAttribute("sessionUser");
            //            //请求的IP
            String ip = request.getRemoteAddr();
            //id
            String ID=  Convert.get32UUID();
            //获取请求参数
            //Object object[] = joinPoint.getArgs();
            Map<String, Object>   map = getControllerMthodDescription(joinPoint);

            SysLogOperate log = new SysLogOperate();
            log.setLogId(ID);
            log.setUserId(user.getUserId());
            log.setUserName(user.getUserName());
            log.setUserIp(ip);
            log.setLogPath(Path);
            log.setLogModule((String) map.get("module"));
            String description= (String) map.get("description");
            if("0".equals(description)){
                log.setLogDesc((String) request.getAttribute("description"));
            }else {
                log.setLogDesc((String) map.get("description"));
            }
            log.setDeptName(user.getDeptId());
            log.setLogLevel("INFO");
            log.setLogDate(new Date());
            Map properties = request.getParameterMap();
            if (properties != null) {
                log.setParameter(JsonUtil.beanToJson(properties));
            }
            iSysLogService.insertOperate(log);
        } catch (Exception e) {
            e.printStackTrace();
        }

       // System.out.println("标记为"+tag.get()+"的方法"+method.getName()+"运行消耗"+(System.currentTimeMillis()-time.get())+"ms");
    }

/*
    @Around("OpLogAopController()")
    public void aroundExec(ProceedingJoinPoint pjp) throws Throwable{
        System.out.println("4444444444444444我是Around，来打酱油的");
        pjp.proceed();
    }
*/

    /**
     *
     * @param joinPoint
     * @return
     * @throws Exception
     */
    public Map<String, Object> getControllerMthodDescription(JoinPoint joinPoint)
            throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        String targetName = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        Object[] arguments = joinPoint.getArgs();
        Class targetClass = Class.forName(targetName);
        Method[] methods = targetClass.getMethods();
        for (Method method : methods) {
            if (method.getName().equals(methodName)) {
                Class[] clazzs = method.getParameterTypes();
                if (clazzs.length == arguments.length) {
                    map.put("module", method.getAnnotation(OpLogAopController.class).module());
                    map.put("methods", method.getAnnotation(OpLogAopController.class).methods());//用户操作
                    String description = method.getAnnotation(OpLogAopController.class).description();
                    map.put("description", description);
                    break;
                }
            }
        }
        return map;
    }
}
